import pandas as pd
from DatetimeUtils import choose_day
from ListUtils import anti_join
import time
"""
营运能力数据
按年度、季度获取
"""

def deal_append(year, quarter, engine, ts):
    """
    通过anti_join函数处理增量数据
    """
    source_list_ = ts.get_operation_data(year, quarter)

    if len(source_list_) > 0:
        source_list_['current_year'] = '%s' %year
        source_list_['current_quarter'] = '%s' %quarter
        source_list_.rename(columns={'code': 'symbol'}, inplace=True)
        # print('source_list_：(%s)' % source_list_)
        sql_ = 'select s.ts_code, s.symbol from stock s '
        stock_list = pd.read_sql(sql_, engine)
        source_list_ = pd.merge(source_list_, stock_list, on='symbol')

        sql_ = 'select s.current_year, s.current_quarter, s.symbol from old_operation_data s WHERE s.current_year = %s' %year + ' and s.current_quarter = %s' %quarter
        target_list_ = pd.read_sql(sql_, engine)
        # print('target_list_：(%s)' % target_list_)
        if len(target_list_) > 0:
            source_list_ = anti_join(source_list_, target_list_, ['symbol', 'current_year', 'current_quarter'])
            if len(source_list_) > 0:
                print('增量：(%s)' % source_list_)
                source_list_.to_sql('old_operation_data', con=engine, index=False, index_label=['symbol', 'current_year', 'current_quarter'], if_exists='append')
                time.sleep(5)
        else:
            print('source_list_：(%s)' % source_list_)
            source_list_.to_sql('old_operation_data', con=engine, index=False, index_label=['symbol', 'current_year', 'current_quarter'], if_exists='append')
            print('数据库内未找到数据则全部添加：(%s)' % source_list_)
            time.sleep(5)




def insert_history_data_operation_date(engine, ts):
    """
    是否查询并保存历史数据
    """
    test_flag = False
    if test_flag:
        deal_append(1999, 1, engine, ts)
    else:
        first_year = 1998 #年报数据从19980930开始 也就是1998年3季度
        current_year = choose_day(0).strftime('%Y')
        for i in range(first_year, int(current_year)):
            quarter = 0
            if i == 1998:
                quarter = 2
            for j in range(quarter, 4):
                try:
                    deal_append(i, j+1, engine, ts)
                except Exception as ex:
                    print('接口调用失败')
                    print(ex)
                    pass



def update_current_data_operation_date(engine, ts):
    """
    更新当前数据，后续使用定时器
    """
    first_year = choose_day(1).strftime('%Y')  # 年报数据从19980930开始 也就是1998年3季度
    current_year = choose_day(0).strftime('%Y')
    for i in range(int(first_year), int(current_year)+1):
        for j in range(0, 4):
            try:
                deal_append(i, j + 1, engine, ts)
            except Exception as ex:
                print('接口调用失败')
                print(ex)
                pass